import React, { useEffect, useMemo, useState } from 'react';
import "../css/index.scss"
import { SearchBar, ConfigProvider, Ellipsis } from '@nutui/nutui-react';
import { Category, Cart } from '@nutui/icons-react'
import axios from "axios";
import GoodItem from './GoodItem';
import { useSearchParams } from 'react-router-dom';
const Index = () => {
    // 请求传参传递过来类别数组的下标
    let [catei, setCatei] = useSearchParams()
    let id=Number(catei.get("id"))
    // console.log(id);
    // 按照价格排序
    let [pricesort, setPriceSort] = useState(false)
    // 商品类别数组
    let [catelist, setCatelist] = useState([])
    // 默认类别数组第一个下标
    // let [cateindex, setCateindex] = useState(0)
    let [cateindex, setCateindex] = useState(id|| 0)
    // 商品的二级类别数组
    let [subcate, setSubcate] = useState([])
    // 默认二级类别数组第一个下标
    let [subcateindex, setSubcateindex] = useState(0)
    // 获取商品列表接口
    let getcate = async () => {
        let { data: { data } } = await axios.get("http://localhost:3000/limengxi/getcate")
        // console.log(data);
        //根据cateindex来进行截取组合
        let arrs = data.slice(0, cateindex)
        let arre = data.slice(cateindex)
        let newarr = [...arre, ...arrs]
        // console.log(newarr);
        // 设置商品类别数组
        setCatelist(newarr)
        // setCatelist(data)
        setCateindex(0)
    }
    // 获取默认第一个类别的商品数据
    let getgoods = async () => {
        let cateid = catelist[cateindex]._id
        let { data: { arr } } = await axios.get("http://localhost:3000/limengxi/getgoods?cateid=" + cateid)
        // console.log(arr);
        // 默认展示第一个二级类别的商品
        setSubcate(arr)
    }
    // 全部按钮的显式与否
    let [allshow, setAllshow] = useState(false)
    // 直接监听商品类别数组
    useMemo(() => {
        // console.log("一级商品类别更改，下标更改", cateindex);
        if (catelist.length > 5) {
            setAllshow(true)
        } else {
            setAllshow(false)
        }
        if (catelist.length > 0) {
            getgoods()
        }
    }, [catelist])
    // 直接监听二级商品类别数组下标
    useMemo(() => {
        if(catelist.length>0){
            getgoods()
        }
    }, [cateindex])
    useEffect(() => {
        getcate()
        // changeindex()
    }, [])
    let changecateindex = (index) => {
        setCateindex(index)
        // 直接截取数组,从index下标开始截取
        let arrs = catelist.slice(0, index)
        let arre = catelist.slice(index)
        let newarr = [...arre, ...arrs]
        setCatelist(newarr)
        setAllshow(true)
        setCateindex(0)
    }
    let xiao = () => {
        let newarrr = [...subcate]
        let arrsortsalesnum = newarrr[subcateindex].goods.sort((a, b) => {
            return a.salesnum - b.salesnum
        })
        newarrr[subcateindex].goods = arrsortsalesnum
        setSubcate(newarrr)
    }
    let jiage = () => {
        setPriceSort(!pricesort)
        let newarrr = [...subcate]
        if (pricesort) {
            let arrsortprice = newarrr[subcateindex].goods.sort((a, b) => {
                return a.price - b.price
            })
            newarrr[subcateindex].goods = arrsortprice
            setSubcate(newarrr)
        } else {
            let arrsortprice = newarrr[subcateindex].goods.sort((a, b) => {
                return b.price - a.price
            })
            newarrr[subcateindex].goods = arrsortprice
            setSubcate(newarrr)
        }
    }
    let addshopcar = (item) => {
        // console.log(item);
        // 获取当前商品的id
        let id = item._id
        // item.buyNum += 1
        // 将商品添加到后端购物车数据库中
        // -----------------------------------------------------------------------------------------待办，将id传到后端，判断是否存在该商品，然后进行加一
        // 从购物车数组中找到这个商品，并更新购买数量
        let newarrr = [...subcate]
        // 从当前数组中找到这个商品，并更新购买数量
        let changeid = newarrr[subcateindex].goods.findIndex((item) => {
            return item._id === id
        })
        newarrr[subcateindex].goods[changeid] = item
        setSubcate(newarrr)
    }
    // let tule = (index) => {
    //     setCateindex(index)
    // }
    return (
        //  分类页面
        <div className='cate_page'>
            {/* 搜索框 */}
            <div className='cate_search'>
                <ConfigProvider
                    theme={{
                        nutuiSearchbarBackground: 'white',
                        nutuiSearchbarInputBackground: 'red',
                        nutuiSearchbarInputTextAlign: 'red',
                        nutuiSearchbarContentBackground: 'rgb(242, 242, 242)',
                    }}
                >
                    <SearchBar shape="round" maxLength={15} placeholder="小米" />
                </ConfigProvider>
            </div>
            {/* 商品类别框 */}
            <div className='cate_list'>
                {/* 商品类别 */}
                {allshow ? catelist.slice(0, 5).map((item, index) => {
                    return <div
                        className={cateindex === index ? "catecolor cate_list_item" : "cate_list_item"}
                        key={item._id}
                        onClick={() => {
                            setCateindex(index)
                            // tule(index)
                            
                        }}>
                        <div
                            className="img_box"
                            style={{ backgroundColor: cateindex === index ? 'rgba(137, 218, 173, 0.603)' : 'rgba(165, 166, 165, 0.548)' }}>
                            <img src={item.img} alt="" />
                        </div>
                        <p>{item.name}</p>
                    </div>
                }) : <div className='zhan_box'>
                    {catelist.map((item, index) => {
                        return <div
                            className={cateindex === index ? "catecolor cate_list_item1" : "cate_list_item1"}
                            key={item._id}
                            onClick={() => {
                               
                                changecateindex(index)
                                // setSubcate(item.children)
                            }}>
                            <div
                                className="img_box"
                                style={{ backgroundColor: cateindex === index ? 'rgba(137, 218, 173, 0.603)' : 'rgba(165, 166, 165, 0.548)' }}>
                                <img src={item.img} alt="" />
                            </div>
                            <p>{item.name}</p>
                        </div>
                    })}
                </div>
                }
                {allshow ? <div className='all_cate'>
                    <p>全部</p>
                    <Category onClick={() => {
                        setCateindex(0)
                        setAllshow(false)
                    }} />
                </div> : null}

            </div>
            {/* 商品二级分类和商品盒子 */}
            <div className='good_box'>
                {/* 二级分类盒子 */}
                <div className='sub_cate'>
                    <ul>
                        {subcate.map((item, index) => (
                            <li key={index}
                                className={subcateindex === index ? "li_active" : ""}
                                onClick={() => {
                                    setSubcateindex(index)
                                }}>
                                {item.subCategory}
                            </li>
                        ))
                        }
                    </ul>
                </div>
                {/* 商品盒子 */}
                <div className='good_list'>
                    <img
                        src="https://cdn7.axureshop.com/demo/2043174/images/%E5%88%86%E7%B1%BB/u744.png"
                    ></img>
                    {/* 筛选盒子 */}
                    <div className='filter_box'>
                        <span>推荐</span><p><span onClick={() => { xiao() }}>销量</span>&nbsp;<span onClick={() => { jiage() }}>价格⬆⬇</span></p>
                    </div>
                    {/* 商品盒子 */}
                    <div className='show_box'>
                        {/* 商品渲染 */}
                        {subcate.length > 0 && subcate[subcateindex].goods.map((item, index) => (
                            <GoodItem obj={item} addshopcar={addshopcar} key={item._id}></GoodItem>
                            // <div className='good_item' key={item._id}>
                            //     <img src={item.img} alt="" />
                            //     <div className='good_info'>
                            //         <p className='good_name'>{item.name}&nbsp;{item.specTitle}</p>
                            //         {/* <p>{item.desc}</p> */}
                            //         <Ellipsis content={item.desc}
                            //             direction="end"
                            //             style={{ color: '#808080' }} />
                            //         <div className='good_price_box'>
                            //             <p className='good_price'>￥{item.price}</p>
                            //             <div className='good_cart'>
                            //                 <Cart onClick={() => {
                            //                     // 点击加入购物车，数量加一
                            //                     addshopcar(item)
                            //                 }} /><span className='add_num'>{item.buyNum>0?item.buyNum:null}</span>
                            //             </div>
                            //         </div>

                            //     </div>
                            // </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Index;
